const db = wx.cloud.database();

let plugin = requirePlugin('routePlan');
const key = 'YIGBZ-O3DRU-HVPVR-2F34E-NHPB3-S4BCJ';  //使用在腾讯位置服务申请的key
const referer = 'Agriculture';   //调用插件的app的名称


Page({

   data: {
        show:false,
        containter:null,
        object:{},
        collection:"",
        endPoint :'' ,
        condition:0,
        user:{},
        star:"",
        message:""
  },

  onLoad: function (options) {
 
    let that = this
    const {jsonStr} = options;
    const detail= JSON.parse( decodeURIComponent(jsonStr) )

    that.setData({
      object: detail || {} ,
      endPoint:JSON.stringify({
                  'name':detail.location.name,
                  'latitude':detail.location.latitude,
                  'longitude':detail.location.longitude
                }),
     condition:options.condition
    })
    var usere = wx.getStorageSync('userFlag')
    this.setData({
        user:usere
    })

    var name = detail.user.name.substring(0,1);
    if(detail.user.gender == 1){
        name +='先生'
    }else{
        name +='女士'
    }
    that.setData({
        ['object.user.name']:name
    })
    var flag = wx.getStorageSync('userFlag').flag; 
    if(flag==0) 
    {return }
    
    db.collection('collection').where({
      _openid:wx.getStorageSync('userFlag').user._id,
      'object._id':detail._id
    }).get().then(res=>{
        if(res.data.length != 0){
          that.setData({
            star:"/icons/collection.png",
            collection:true
          })
        }else{
          that.setData({
            star:"star-o",
            collection:false
          })
        }
    })
  },

  collection(){
    var condition = this.data.condition;
    var object = this.data.object;
    var openid =  wx.getStorageSync('userFlag').user._id;
    var c= this.data.collection;
    if(c){
        wx.showLoading({
            title: '加载中',
          })
      this.setData({
        star:"star-o",
        collection:false
      })
      wx.cloud.callFunction({
        name:'removeCollection',
        data:{
          openid : openid,
          object_id : [object._id]
        }
      }).then(res =>{
        wx.showToast({
          title: '取消收藏',
        })
        console.log(res)
      })
    }else{
        wx.showLoading({
          title: '加载中',
        })
      this.setData({
        star:"/icons/collection.png",
        collection:true
      })
      db.collection("collection").add({
        data :{
          condition:condition,
          object:object,
        }
      }).then(res=>{
          wx.showToast({
            title: '收藏成功',
          })
      })
    }
  },

  goto(){
      wx.navigateTo({
        url: 'plugin://routePlan/index?key=' + key + '&referer=' + referer + '&endPoint=' + this.data.endPoint
    });
  },
  async viewVR(){
      var vr = this.data.object.VR; 

    if(vr.length!=0){
        var path = await this.path(vr);
        wx.navigateTo({
          url: '/pages/vr/vr?id='+path,
        })
    }else{
        wx.showToast({
          title: '对方还未提供全景图',
          icon:"none"
        })
    }
  },
  previewImage:function(e){

        var imgUrl = e.currentTarget.dataset.src; //获取当前点击的图片
        wx.previewImage({
            current: imgUrl, //当前图片地址
            urls: [imgUrl], //一张图写法
            success: function(res) {},
            fail: function(res) {},
            complete: function(res) {},
        })
  },

    oncli1() {
        this.setData({
            show:true,
            message:"土地流转需要和拥有土地使用权的人员进行协商，以及向有关部门提交申请。具体请查看国家政策"
        })
    },
    oncli2() {
        this.setData({
            show:true,
            message:"在您确定要使用之前请您仔细了解该机器的注意事项，以免造成损失!"
        })
    },

  onReady: function () {
   this.setData({
     containter:()=>wx.createSelectorQuery().select('#containter'),
   });
  },

  onShow: function () {
    var flag = wx.getStorageSync('userFlag').flag; 
    if(flag==0) {
        wx.showModal({
            title: '提示',
            content: '你还未完善个人信息，是否立刻去完善？',
            success (res) {
                if (res.confirm) {
                    wx.switchTab({
                        url: '/pages/user/index',
                    })
                } else if (res.cancel) {
                            wx.switchTab({
                                url: '/pages/index/index',
                            })
                        }
                }
        })
    }
  },

  consult(){
      const {object} = this.data;
    wx.navigateTo({
      url: '/pages/chat/chat?id='+object.user._id,
    })
  },
  onPullDownRefresh:function () {
    setTimeout(()=>{ wx.stopPullDownRefresh({
    success: (res) => {}})},1000)  
},

async path(fileid){
    var path="";
    await wx.cloud.getTempFileURL({
        fileList: [fileid]
    }).then(res=>{
        path = res.fileList[0].tempFileURL;
    })
    return path;
}
})